package com.customization.huangwm.workflowNodeAction.SW003;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.api.customization.huangwm.dao.SW003.LoggingDao;
import com.customization.huangwm.utils.DBTools;
import com.customization.huangwm.utils.HttpRequest;
import com.customization.huangwm.utils.LogTool;

import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import weaver.general.BaseBean;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.Property;
import weaver.soa.workflow.request.RequestInfo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Huangwm
 * @description 資產報废流程 創建針對報廢的資產更改狀態為報廢中，並且校驗不允許重複報廢
 * 歸檔後修改報廢中的資產為已報廢，對接用友扣減對應物料的數量-1？不需要对接
 * 修改所关联的借用记录 更新归还数量 2023年10月26日 取消资产浏览按钮003_Assets条件where assetStatus='Operating'
 */
public class AssetsReimbursement implements Action {

    private LogTool log = new LogTool("/log/SW003/huangwm/WfAction/AssetsReimbursement", false);
    private DBTools dbTools = new DBTools();
    private LoggingDao loggingDao = new LoggingDao();
    public String type;//submit_create,submit_review,submit_end

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    @Override
    public String execute(RequestInfo requestInfo) {
        String requestid = requestInfo.getRequestid();
        String nodeType = requestInfo.getRequestManager().getNodetype();
        String src = requestInfo.getRequestManager().getSrc();
        int creater = requestInfo.getRequestManager().getCreater();
        log.writeLog("資產報廢程>>>" + requestid + ">>" + nodeType + ">>" + src + ">>" + type);
        if (type.equals("") || (!type.equals("submit_create") && !type.equals("submit_review") && !type.equals("submit_end") && !type.equals("submit_reject"))) {
            requestInfo.getRequestManager().setMessageid(requestid);
            requestInfo.getRequestManager().setMessagecontent("未獲取到Action參數type或參數值不正確,請聯繫管理員檢查後台接口動作設置!;");
            return FAILURE_AND_CONTINUE;
        }

        RecordSet rs1 = new RecordSet();

        String tableName = requestInfo.getRequestManager().getBillTableName();
        String billid = requestInfo.getRequestManager().getBillid() + "";
        Map<String,String> main = new HashMap<>();
        Property[] properties = requestInfo.getMainTableInfo().getProperty();
        for (Property property : properties){
            main.put(property.getName().toLowerCase(),property.getValue());
        }
        int userid = requestInfo.getRequestManager().getUserId();
        String operator = main.getOrDefault("applicationuser",creater+"");//申请人

        RecordSetTrans rst1 = new RecordSetTrans();
        rst1.setAutoCommit(false);

        if (src.equals("reject")) {
            RecordSetTrans rst2 = new RecordSetTrans();
            rst2.setAutoCommit(false);
            try {
                //更新資產狀態為借出 1→oldStatus
                //String sql1 = " update uf_003_AssetInfo2 set assetStatus=oldStatus from "+tableName+"_dt1 dt where dt.mainAssetCode=uf_003_AssetInfo2.id and dt.methodOfHanding=1  and mainid="+billid;
                String sql1 = " update uf_003_AssetInfo2 set assetStatus=oldStatus from " + tableName + "_dt1 dt where dt.mainAssetCode=uf_003_AssetInfo2.id and mainid=" + billid;
                //更新物料申領記錄中的歸還中數量-1
                String sql2 = "update  uf_003_applicationRecord  set quantityInReturn=NVL(quantityInReturn,0)-1 from  "+tableName+"_dt1 dt "+
                        "\n where  uf_003_applicationRecord.mainAssetCode=dt.mainAssetCode and uf_003_applicationRecord.applicationUser="+creater+
                        "\n and mainid="+billid+" and (oper_staus is null or oper_staus=0)";
                if (rst2.getDBType().equals("oracle")) {
                    sql1 = "update uf_003_AssetInfo2 set assetStatus=(select oldStatus from " + tableName + "_dt1 where uf_003_AssetInfo2.id=mainAssetCode and mainid=" + billid + ")" +
                            "\n where id in (select mainAssetCode from " + tableName + "_dt1 where mainid=" + billid + ")";
                    sql2 = "update uf_003_applicationRecord  set quantityInReturn=NVL(quantityInReturn,0)-1\n" +
                            " where MAINASSETCODE in( select mainAssetCode  from  "+tableName+"_dt1 where mainid="+billid+") " +
                            " and (oper_staus is null or oper_staus=0)";
                }
                log.writeLog("退回更新資產狀態為借出SQL：" + sql1);
                log.writeLog("退回釋放物料申領記錄歸還中數量SQL："+sql2);
                boolean result1 = rst2.execute(sql1);
                boolean result2 = rst2.execute(sql2);
                if (!result2) {
                    rst2.rollback();
                    requestInfo.getRequestManager().setMessageid(requestid);
                    requestInfo.getRequestManager().setMessagecontent("退回釋放物料申領記錄歸還中數量SQL異常;" + sql2);
                    return FAILURE_AND_CONTINUE;
                }
                if (!result1) {
                    rst2.rollback();
                    requestInfo.getRequestManager().setMessageid(requestid);
                    requestInfo.getRequestManager().setMessagecontent("退回更新資產狀態為借出失敗,執行SQL異常;" + sql1);
                    return FAILURE_AND_CONTINUE;
                } else {
                    rst2.commit();
                    return SUCCESS;
                }
            } catch (Exception e) {
                rst2.rollback();
                e.printStackTrace();
                requestInfo.getRequestManager().setMessageid(requestid);
                requestInfo.getRequestManager().setMessagecontent("退回更新資產狀態為借出失敗,程序異常;\n" + e.getMessage());
                return FAILURE_AND_CONTINUE;
            }
        } else if (type.equals("submit_create")) {
            try {
                //查詢關聯報廢的資產狀態，不為1（借出）則不允許報廢--新报废逻辑中不使用
                //String sql1 = " select ass.assetStatus from "+tableName+"_dt1 dt left join uf_003_AssetInfo2 ass"+
                //"\n on dt.mainAssetCode=ass.id where mainid="+billid;
                //更新資產狀態為報廢中 6→F
                //String sql2 = " update uf_003_AssetInfo2 set assetStatus='F' from "+tableName+"_dt1 dt where dt.mainAssetCode=uf_003_AssetInfo2.id and dt.methodOfHanding=1  and mainid="+billid;
                String sql2 = " update uf_003_AssetInfo2 set assetStatus='Inactive' from " + tableName + "_dt1 dt where dt.mainAssetCode=uf_003_AssetInfo2.id and mainid=" + billid;

                //更新物料申領記錄中的歸還中數量+1--
                String sql3 = "update  uf_003_applicationRecord  set quantityInReturn=NVL(quantityInReturn,0)+1 from  "+tableName+"_dt1 dt "+
                "\n where  uf_003_applicationRecord.mainAssetCode=dt.mainAssetCode and uf_003_applicationRecord.applicationUser="+creater+
                "\n and mainid="+billid+" and (oper_staus is null or oper_staus=0)";
                if (rs1.getDBType().equals("oracle")) {
                    sql2 = "update uf_003_AssetInfo2 set assetStatus=(select 'Inactive' from " + tableName + "_dt1 dt where  uf_003_AssetInfo2.id=mainAssetCode and dt.mainid=" + billid + ")" +
                            "\n where id in(select mainAssetCode from  " + tableName + "_dt1 where mainid=" + billid + ")";
                    sql3 = "update uf_003_applicationRecord  set quantityInReturn=NVL(quantityInReturn,0)+1\n" +
                            " where MAINASSETCODE in( select mainAssetCode  from  "+tableName+"_dt1 where mainid="+billid+") " +
                            " and (oper_staus is null or oper_staus=0)";
                }
                //log.writeLog("創建提交查詢關聯報廢的資產狀態SQL："+sql1);
                log.writeLog("創建提交更新資產狀態為報廢中SQL：" + sql2);
                log.writeLog("創建提交更新物料申領記錄中的歸還中數量SQL："+sql3);

                boolean result1 = rst1.execute(sql2);
                boolean result2 = rst1.execute(sql3);
                if (!result2) {
                    rst1.rollback();
                    requestInfo.getRequestManager().setMessageid(requestid);
                    requestInfo.getRequestManager().setMessagecontent("創建提交更新物料申領記錄中的歸還中數量SQL異常;" + sql3);
                    return FAILURE_AND_CONTINUE;
                }
                if (!result1) {
                    rst1.rollback();
                    requestInfo.getRequestManager().setMessageid(requestid);
                    requestInfo.getRequestManager().setMessagecontent("創建提交更新資產狀態為報廢中SQL異常;" + sql2);
                    return FAILURE_AND_CONTINUE;
                } else {
                    rst1.commit();
                    return SUCCESS;
                }
            } catch (Exception e) {
                rst1.rollback();
                e.printStackTrace();
                requestInfo.getRequestManager().setMessageid(requestid);
                requestInfo.getRequestManager().setMessagecontent("創建提交檢查/更新資產失敗,程序異常;\n" + e.getMessage());
                return FAILURE_AND_CONTINUE;
            }
        } else if (type.equals("submit_end")) {
            try {
                //更新資產表狀態為已報廢3→D
                String sql1 = " update uf_003_AssetInfo2 set assetStatus='Decommission' from " + tableName + "_dt1 dt where dt.mainAssetCode=uf_003_AssetInfo2.id  and mainid=" + billid;
                //更新物料申領中所關聯的資產記錄為已歸還 歸還中數量-1 已歸還數量+1
                String sql2 = "update uf_003_applicationRecord set quantityInReturn=NVL(quantityInReturn,0)-1,returnQuantity=NVL(returnQuantity,0)+1,oper_staus=1"+
                "\n from "+tableName+"_dt1 dt where dt.mainAssetCode=uf_003_applicationRecord.mainAssetCode"+
                "\n and uf_003_applicationRecord.applicationUser="+creater+" and mainid="+billid+" and (oper_staus is null or oper_staus=0)";
                //报废后更新物料库存数量？？需要判断当前资产是否被领用，不被领用的才要更新
                if (rst1.getDBType().equals("oracle")) {
                    sql1 = "update uf_003_AssetInfo2 set assetStatus=(select 'Decommission' from " + tableName + "_dt1 dt where  uf_003_AssetInfo2.id=mainAssetCode and dt.mainid=" + billid + ")" +
                            "\n where id in(select mainAssetCode from  " + tableName + "_dt1 where mainid=" + billid + ")";
                    sql2 = "update uf_003_applicationRecord  set quantityInReturn=NVL(quantityInReturn,0)-1,returnQuantity=NVL(returnQuantity,0)+1,oper_staus=1\n" +
                            " where MAINASSETCODE in( select mainAssetCode  from  "+tableName+"_dt1 where mainid="+billid+") " +
                            " and (oper_staus is null or oper_staus=0)";
                }
                log.writeLog("歸檔更新資產表狀態為已報廢SQL：" + sql1);
                log.writeLog("歸檔更新物料申領中所關聯的資產記錄為SQL："+sql2);
                boolean result1 = rst1.execute(sql1);
                boolean result2 = rst1.execute(sql2);
                log.writeLog("SQL執行結果;result1=" + result1+";result2="+result2);
                if (!result2) {
                    rst1.rollback();
                    requestInfo.getRequestManager().setMessageid(requestid);
                    requestInfo.getRequestManager().setMessagecontent("归档更新物料申領記錄中的歸還中數量SQL異常;" + sql2);
                    return FAILURE_AND_CONTINUE;
                }
                if (!result1) {
                    rst1.rollback();
                    requestInfo.getRequestManager().setMessageid(requestid);
                    requestInfo.getRequestManager().setMessagecontent("歸檔更新資產為已報廢失敗,SQL執行異常;" + sql1);
                    return FAILURE_AND_CONTINUE;
                }

                RecordSet rs = new RecordSet();
                RecordSet rs2 = new RecordSet();
                RecordSet rs3 = new RecordSet();
                List<Map<String, String>> logList = new ArrayList<>();
                rs.execute("select * from "+tableName+"_dt1 where mainid="+billid);
                while(rs.next()){
                    String detail_id = rs.getString("id");
                    String mainAssetCode = rs.getString("mainAssetCode");
                    String mainAssetName = rs.getString("mainAssetName");
                    String oldStatus = rs.getString("oldStatus");
                    String field1 = rs.getString("field1");
                    log.writeLog("mainAssetName:"+mainAssetName+"   oldStatus:"+oldStatus);
                    String assetid = dbTools.getAssetid(mainAssetCode);
                    Map<String,String> assetInfo = dbTools.getAssetAllFieldoByID(rs3,assetid);
                    //如果oldStatus還在庫存狀態則減少庫存
                    if(oldStatus.equals("Stock")){
                        String sql = "select * from uf_003_WarehouseNum where assetCode="+assetid+" and wareHouse="+field1;
                        log.writeLog("判断是否有仓库库存 "+sql);
                        rs2.execute(sql);
                        if(rs2.next()){
                            String wid = rs2.getString("id");
                            //1 減少物料主庫存
                            String mainsql = "update uf_003_AssteInfo set InventoryQuantity=InventoryQuantity-1,usedQuantity=usedQuantity+1 where id="+assetid;
                            log.writeLog("減少物料主庫存："+mainsql);
                            boolean f1 = rst1.execute(mainsql);
                            if(!f1){
                                rst1.rollback();
                                requestInfo.getRequestManager().setMessageid(requestid);
                                requestInfo.getRequestManager().setMessagecontent("資產名稱:"+mainAssetName+"更新物料主庫存失敗("+field1+")");
                                return FAILURE_AND_CONTINUE;
                            }
                            //2 減少物料倉庫庫存
                            String detailsql = "update uf_003_WarehouseNum set num3=num3-1,num2=num2+1 where id="+wid;
                            log.writeLog("減少物料倉庫庫存："+detailsql);
                            boolean f = rst1.execute(detailsql);
                            if(!f){
                                rst1.rollback();
                                requestInfo.getRequestManager().setMessageid(requestid);
                                requestInfo.getRequestManager().setMessagecontent("資產名稱:"+mainAssetName+"更新倉庫庫存失敗("+field1+")");
                                return FAILURE_AND_CONTINUE;
                            }
                        }else{
                            rst1.rollback();
                            requestInfo.getRequestManager().setMessageid(requestid);
                            requestInfo.getRequestManager().setMessagecontent("資產名稱:"+mainAssetName+"未查找到對應的物料倉庫庫存("+field1+")");
                            return FAILURE_AND_CONTINUE;
                        }

                        Map<String, String> logMap = new HashMap();
                        logMap.put("assetCode", assetInfo.get("assetcode"));
                        logMap.put("assetName", assetInfo.get("assetname"));
                        logMap.put("quantity", "-1");//報廢是減少庫存
                        logMap.put("requestNumber", requestid);
                        logMap.put("reason", "資產名稱:"+mainAssetName+"報廢-1");
                        logMap.put("field1", field1);
                        logMap.put("field2", "");
                        logMap.put("detail_id",detail_id);
                        logList.add(logMap);
                    }

                }
                for (int i = 0; i < logList.size(); i++) {
                    Map<String, String> log = logList.get(i);
                    loggingDao.wrtieInventoryLog(rst1,"1", log.get("assetCode"),
                            Double.parseDouble(log.get("quantity")), log.get("requestNumber"),
                            log.get("reason"),log.get("field1"),log.get("field2"),
                            "7",userid+"",operator,log.get("assetName"),billid,log.get("detail_id"));
                }
                rst1.commit();
            } catch (Exception e) {
                rst1.rollback();
                e.printStackTrace();
                requestInfo.getRequestManager().setMessageid(requestid);
                requestInfo.getRequestManager().setMessagecontent("歸檔更新資產為已報廢失敗,程序異常;\n" + e.getMessage());
                return FAILURE_AND_CONTINUE;
            }
        }
        rst1.rollback();
        return SUCCESS;
    }

}
